<template>
  <div class="app-container">
    <el-form :model="form" label-width="80px" ref="form">
      <!-- 题目数据 -->
      <el-row :gutter="0">
        <el-col :span="19">
          <!-- 标题 -->
          <el-row :gutter="0">
            <el-col :span="24">
              <el-form-item prop="examQuestionName" label="题目">
                <el-input placeholder="题目" v-model="form.examQuestionName" class="filter-item" auto-complete="off" @blur="handleFormatQuestionName"/>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 平台、题型 -->
          <el-row :gutter="0">
            <el-col :span="12">
              <el-form-item prop="examQuestionPlatform" label="平台">
                <el-checkbox-group v-model="form.examQuestionPlatformList">
                  <el-checkbox v-for="item in pageData.examQuestionPlatformList" :label="item.value" :key="item.value" disabled>{{item.label}}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="examQuestionType" label="题型">
                <el-radio-group v-model="form.examQuestionType">
                  <el-radio v-for="item in pageData.examQuestionTypeList" :label="item.value" :key="item.value">{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 难易度、考点、审核状态 -->
          <el-row>
            <el-col :span="8">
              <el-form-item prop="examQuestionType" label="难易度">
                <el-radio-group v-model="form.examQuestionDifficultyType">
                  <el-radio v-for="item in pageData.examQuestionDifficultyTypeList" :label="item.value" :key="item.value">{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="examQuestionLabelList" label="标签">
                <el-cascader
                  v-model="form.examQuestionLabelList"
                  :options="pageData.examQuestionLabelList"
                  :props="{ multiple: true, checkStrictly: true }"
                  clearable filterable></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="examQuestionType" label="审核">
                <el-radio-group v-model="form.examQuestionStatus">
                  <el-radio v-for="item in pageData.examQuestionStatusList" :label="item.value" :key="item.value">{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 地域、题库、出题人、正确答案 -->
          <el-row :gutter="0">
            <el-col :span="5">
              <el-form-item prop="examQuestionName" label="地域">
                <el-select lass="filter-item" v-model="form.examQuestionTerritoryType" filterable placeholder="请选择">
                  <el-option
                    v-for="item in pageData.examQuestionTerritoryTypeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item prop="examQuestionName" label="题库">
                <el-select lass="filter-item" v-model="form.examQuestionWarehouseId" filterable placeholder="请选择">
                  <el-option
                    v-for="item in pageData.examQuestionWarehouseList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item prop="examQuestionCreateUser" label="出题人">
                <el-input placeholder="出题人" v-model="form.examQuestionCreateUser" class="filter-item" auto-complete="off"/>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item prop="examQuestionEditor" label="编辑">
                <el-input placeholder="编辑" v-model="form.examQuestionEditor" class="filter-item" auto-complete="off"/>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item prop="examQuestionName" label="正确答案">
                <el-input placeholder="正确答案" v-model="form.examQuestionCorrectAnswer" class="filter-item" auto-complete="off" disabled/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <!-- 标题图片 -->
        <el-col :span="5">
          <el-form-item label="首屏图">
            <el-upload
              class="avatar-uploader"
              action="/api/cms/common/uploadFile"
              :show-file-list="false"
              :on-success="handleQuestionImageUploadSuccess">
              <img v-if="form.examQuestionImage" :src="form.examQuestionImage" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" style="line-height: 178px"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 选项数据 -->
      <el-row :gutter="0">
        <!-- 新增按钮 -->
        <el-row :gutter="0">
          <el-col :span="24">
            <el-form-item>
              <el-button type="primary" style="float: left" @click="handleAddOptionButtonClick">新增选项</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 选项列表 -->
        <el-row :gutter="0">
          <div v-for="(item, index) in form.examQuestionOption">
            <el-row :gutter="0">
              <el-col :span="2">
                <el-form-item prop="optionNumber" label="选项编号">
                  <el-input placeholder="大写的英文字母" v-model="item.optionNumber" class="filter-item" auto-complete="off"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="optionName" label="选项文字">
                  <el-input placeholder="选项一" v-model="item.optionName" class="filter-item" auto-complete="off" @blur="handleFormatOptionName(index)"/>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item prop="optionIsTrue" label="是否正确">
                  <el-switch
                    v-model="item.optionIsTrue" :active-value="1" active-color="#13ce66" :inactive-value="0" inactive-color="#ff4949" @change="handleSelectCorrectAnswer(index)">
                  </el-switch>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item prop="optionStatus" label="可用状态">
                  <el-radio v-model="item.optionStatus" :label="0" @change="handleSelectCorrectAnswer">预设</el-radio>
                  <el-radio v-model="item.optionStatus" :label="1" @change="handleSelectCorrectAnswer">发布</el-radio>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item>
                  <el-button type="danger" style="float: left" @click="handleDeleteOptionButtonClick(index)">删除选项</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-row>
      </el-row>
      <!-- 答案解析 -->
      <el-row :gutter="0">
        <el-col :span="24">
          <vue-ueditor-wrap v-model="form.examQuestionInfo" :config="pageData.editorConfig"></vue-ueditor-wrap>
        </el-col>
      </el-row>
      <!-- 锚点占比提示 -->
      <el-row :gutter="0" style="margin-top: 20px">
        <el-col :span="24">
          <el-form-item prop="examQuestionInfo" label="锚点占比">
            <el-input placeholder="提示：随堂小测只有一次答题机会，占培训总成绩50%。" v-model="form.examQuestionHint" class="filter-item" auto-complete="off" type="textarea" :rows="3"/>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 保存按钮 -->
      <el-row :gutter="0">
        <el-col :span="24">
          <el-form-item>
            <el-button type="primary" @click="handleSaveButtonClick">保存题目</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
  // 组件引入
  // 方法工具引入
  import { PermissionsToDetectFormUser } from '@/utils/PermissionsDetect';
  import { getPermission,getName } from '@/utils/UserCookies';
  import { formatTex } from '@/utils/index';
  // 接口引入
  import { loadCmsChinaList,loadCmsExamLabelList,loadCmsExamQuestionWarehouseLabelList,saveCmsExamQuestion } from "@/api/study";
  export default {
    name: "save",
    //import引入的组件需要注入到对象中才能使用
    components: {},
    data() {
      return {
        pageData:{
          examQuestionPlatformList: [
            {label: "易考通", value: "1"},
            {label: "易采通", value: "2"},
            {label: "小程序", value: "3"},
            {label: "锚点", value: "4"}
          ],
          examQuestionTypeList: [
            {label: "单选题", value: 1},
            {label: "多选题", value: 2},
            {label: "判断题", value: 3},
          ],
          examQuestionDifficultyTypeList: [
            {label: "易", value: 1},
            {label: "中", value: 2},
            {label: "难", value: 3}
          ],
          examQuestionStatusList: [
            {label: "未审核", value: -1},
            {label: "未发布", value: 0},
            {label: "发布", value: 1}
          ],
          examQuestionTerritoryTypeList: [],
          examQuestionWarehouseList: [
            {label: "无题库", value: -1},
          ],
          editorConfig: {
            autoHeightEnabled: false,// 编辑器不自动被内容撑高
            initialFrameHeight: 240,// 初始容器高度
            initialFrameWidth: '100%'// 初始容器宽度
          },// 编辑器配置
          examQuestionLabelList: []
        },// 页面配置数据
        form:{
          examQuestionWarehouseId: -1,
          examQuestionName: "",
          examQuestionPlatformList: ["1","2","3","4"],// 页面参数
          examQuestionPlatform: "",// 接口传参
          examQuestionType: 1,
          examQuestionCreateUser: '刘浩',
          examQuestionEditor: "",
          examQuestionDifficultyType: 1,
          examQuestionStatus: 1,
          examQuestionCorrectAnswer: "",
          examQuestionTerritoryType: "110200",
          examQuestionImage: "",
          examQuestionOption: [{
            optionIndex: 1,
            optionNumber: "A",
            optionName: "",
            optionStatus: 1,
            optionIsTrue: 0
          }],
          examQuestionInfo: "",
          examQuestionHint: '提示：随堂小测只有一次答题机会，占培训总成绩50%。',
          examQuestionLabelList: [],// 页面参数
          examQuestionLabel: "",// 接口传参
        },// 页面表单
        formRules: {},// 表单验证
        responseData: {},// 接口响应数据
      }
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods:{
      // 方法函数
      handlePageInit(){
        this.form.examQuestionEditor = getName();
        this.form.examQuestionCreateUser = getName();
        this.loadCmsExamLabelList();
        this.loadCmsChinaList();
        this.loadCmsExamQuestionWarehouseLabelList();
      },// 页面初始化事件
      handleQuestionImageUploadSuccess(response){
        this.form.examQuestionImage = response.data;
      },// 标题图上传成功
      handleFormatQuestionName(){
        this.form.examQuestionName = formatTex(this.form.examQuestionName);
      },// 格式化标题
      handleFormatOptionName(index){
        // 去除左侧空格
        this.form.examQuestionOption[index].optionName = this.form.examQuestionOption[index].optionName.replace(/^\s*/,"");
        // 格式化标点符号
        this.form.examQuestionOption[index].optionName = formatTex(this.form.examQuestionOption[index].optionName);
      },// 格式化选项
      handleAddOptionButtonClick(){
        let number = "";
        if (this.form.examQuestionOption.length === 0) number = "A";
        if (this.form.examQuestionOption.length === 1) number = "B";
        if (this.form.examQuestionOption.length === 2) number = "C";
        if (this.form.examQuestionOption.length === 3) number = "D";
        if (this.form.examQuestionOption.length === 4) number = "E";
        if (this.form.examQuestionOption.length === 5) number = "F";
        let optionData = {
          optionIndex: this.form.examQuestionOption.length + 1,
          optionNumber: number,
          optionName: "",
          optionStatus: 1,
          optionIsTrue: '0'
        };
        this.form.examQuestionOption.push(optionData);
      },// 新增选项
      handleSelectCorrectAnswer(index){
        let correctAnswer = "";
        if (this.form.examQuestionType === 1 || this.form.examQuestionType === 3){// 单选或者判断题只能有一个正确答案
          // 首先关闭所有的正确答案
          for (let i=0; i<this.form.examQuestionOption.length; i++){
            this.form.examQuestionOption[i].optionIsTrue = 0;
          }
          // 开启当前选择的正确答案
          this.form.examQuestionOption[index].optionIsTrue = 1;
        }
        // 遍历获取正确答案拼接字段
        for (let i=0; i<this.form.examQuestionOption.length; i++){
          if (this.form.examQuestionOption[i].optionIsTrue && this.form.examQuestionOption[i].optionStatus === 1){
            correctAnswer += ","+this.form.examQuestionOption[i].optionNumber;
          }
        }
        this.form.examQuestionCorrectAnswer = correctAnswer;
        if (correctAnswer !== ''){
          let answer = [];
          let answerList = correctAnswer.split(",");
          for (let i=0; i<answerList.length; i++){
            if (answerList[i] !== ''){
              answer.push(answerList[i]);
            }
          }
          this.form.examQuestionCorrectAnswer = answer.toString();
        }
      },// 选择正确答案
      handleDeleteOptionButtonClick(index){
        if ((this.form.examQuestionType === 1 || this.form.examQuestionType === 3) && this.form.examQuestionCorrectAnswer !== ""){// 单选或多选只有一个正确答案
          // 获取当前所选正确答案的下标
          let correctAnswerIndex = -1;
          for (let i=0; i<this.form.examQuestionOption.length; i++){
            if (this.form.examQuestionOption[i].optionNumber === this.form.examQuestionCorrectAnswer){
              correctAnswerIndex = i;
            }
          }
          if (correctAnswerIndex === index){
            // 当前的正确答案已被删除
            this.form.examQuestionCorrectAnswer = "";
            // 首先关闭所有的正确答案
            for (let i=0; i<this.form.examQuestionOption.length; i++){
              this.form.examQuestionOption[i].optionIsTrue = 0;
            }
          }
        }
        // 删除选项数据
        this.form.examQuestionOption.splice(index,1);
        // 重置选项编号
        if (this.form.examQuestionOption.length > 0){
          for (let i=0; i<this.form.examQuestionOption.length; i++){
            if (i === 0){
              this.form.examQuestionOption[i].optionNumber = "A";
              this.form.examQuestionOption[i].optionIndex = i+1;
            }
            if (i === 1){
              this.form.examQuestionOption[i].optionNumber = "B";
              this.form.examQuestionOption[i].optionIndex = i+1;
            }
            if (i === 2){
              this.form.examQuestionOption[i].optionNumber = "C";
              this.form.examQuestionOption[i].optionIndex = i+1;
            }
            if (i === 3){
              this.form.examQuestionOption[i].optionNumber = "D";
              this.form.examQuestionOption[i].optionIndex = i+1;
            }
            if (i === 4){
              this.form.examQuestionOption[i].optionNumber = "E";
              this.form.examQuestionOption[i].optionIndex = i+1;
            }
            if (i === 5){
              this.form.examQuestionOption[i].optionNumber = "F";
              this.form.examQuestionOption[i].optionIndex = i+1;
            }
          }
        }
        if (this.form.examQuestionType === 2){
          // 重置多选的正确答案
          this.handleSelectCorrectAnswer();
        }
      },// 删除选项
      handleSaveButtonClick(){
        if (this.form.examQuestionCorrectAnswer == ''){
          this.$message.warning("请至少选择一个正确答案");
          return;
        }
        if (this.form.examQuestionType == 2){
          if (this.form.examQuestionCorrectAnswer.split(",").length < 2){
            this.$message.warning("多选题至少有两个正确答案");
            return;
          }
        }
        if (this.form.examQuestionType == 3 && this.form.examQuestionOption.length > 2){
          this.$message.warning("判断题只能有两个选项");
          return;
        }
        if (PermissionsToDetectFormUser(getPermission(), "610001")){
          this.$confirm('此操作将会保存当前数据, 请核对后继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.form.examQuestionPlatform = this.form.examQuestionPlatformList.toString();
            // 格式化考题标签信息
            let array = [];
            for (let i=0;i<this.form.examQuestionLabelList.length;i++){
              for (let j=0;j<this.form.examQuestionLabelList[i].length;j++){
                array.push(this.form.examQuestionLabelList[i][j]);
              }
            }
            // 数组去重
            array = array.filter(function(item,index){
              return array.indexOf(item,0) === index;
            });
            this.form.examQuestionLabel = array.toString();
            this.saveCmsExamQuestion();
          }).catch((cancel) => {
            console.log(cancel);
            this.$message.info('已取消操作');
          });
        }  else {
          this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
        }
      },// 保存按钮点击事件
      // 接口
      loadCmsExamLabelList(){
        loadCmsExamLabelList().then(response => {
          if (response.code === "200"){
            this.pageData.examQuestionLabelList = response.data;
            this.pageData.loading = false;
          } else {
            this.$message.warning(response.message);
          }
        }).catch(error => {
          console.log(error);
          this.$message.error(error);
        })
      },// 获取考点标签数据
      loadCmsChinaList(){
        loadCmsChinaList().then(response => {
          if (response.code === "200"){
            this.pageData.examQuestionTerritoryTypeList = response.data;
          } else {
            console.log(response.message);
            this.$message.warning(response.message);
          }
        }).catch(error =>{
          console.log(error);
          this.$message.error(error);
        });
      },// 获取地区字典列表
      loadCmsExamQuestionWarehouseLabelList(){
        loadCmsExamQuestionWarehouseLabelList().then(response => {
          if (response.code === "200"){
            this.pageData.examQuestionWarehouseList = this.pageData.examQuestionWarehouseList.concat(response.data);
          } else {
            this.$message.warning(response.message);
          }
        }).catch(error => {
          console.log(error);
          this.$message.error(error);
        })
      },// 获取题库字典列表
      saveCmsExamQuestion(){
        saveCmsExamQuestion(this.form).then(response => {
          if (response.code === "200"){
            this.$message.success("题目新增成功");
            this.$jump.push({path: '/study/question'});
          } else {
            this.$message.warning(response.message);
          }
        }).catch(error => {
          console.log(error);
          this.$message.error(error);
        })
      },// 保存题目数据
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created: function () {
      let _this = this;
      // 进行初始化数据读取
      setTimeout(function () {
        _this.handlePageInit();
      }, 800);
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {},
    beforeCreate() {}, //生命周期 - 创建之前
    beforeMount() {}, //生命周期 - 挂载之前
    beforeUpdate() {}, //生命周期 - 更新之前
    updated() {}, //生命周期 - 更新之后
    beforeDestroy() {}, //生命周期 - 销毁之前
    destroyed() {}, //生命周期 - 销毁完成
    activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
  };
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
</style>
